// pages/login/login.js
const app = getApp();
const request = require('../../utils/request');
const Toast = require('../../utils/toast');

Page({
  data: {
    loginType: 'guest', // guest-游客模式, account-账号密码, phone-手机验证码
    username: '',
    password: '',
    phone: '',
    smsCode: '',
    countdown: 0,
    sending: false,
    systemName: '',
    systemVersion: ''
  },

  onLoad(options) {
    // 加载系统配置
    this.loadSystemInfo();
    
    // 检查是否已登录
    const token = wx.getStorageSync('token');
    if (token) {
      // 已登录，跳转到首页
      wx.switchTab({
        url: '/pages/index/index'
      });
    }
  },

  // 加载系统信息
  loadSystemInfo() {
    const config = app.globalData.systemConfig || wx.getStorageSync('systemConfig');
    if (config) {
      this.setData({
        systemName: config.system_name,
        systemVersion: config.system_version
      });
    }
  },

  // 切换登录方式
  switchLoginType(e) {
    this.setData({
      loginType: e.currentTarget.dataset.type
    });
  },

  // 输入用户名
  inputUsername(e) {
    this.setData({
      username: e.detail.value
    });
  },

  // 输入密码
  inputPassword(e) {
    this.setData({
      password: e.detail.value
    });
  },

  // 输入手机号
  inputPhone(e) {
    this.setData({
      phone: e.detail.value
    });
  },

  // 输入验证码
  inputSmsCode(e) {
    this.setData({
      smsCode: e.detail.value
    });
  },

  // 游客模式登录（无需微信授权）
  async guestLogin() {
    Toast.loading('登录中...');

    try {
      // 直接调用后端游客登录接口（无需微信授权）
      const res = await request.post('/user-auth/guest-login', {});

      Toast.hideLoading();

      if (res.success) {
        // 保存token和用户信息
        wx.setStorageSync('token', res.data.token);
        wx.setStorageSync('userInfo', res.data.user);
        app.globalData.userInfo = res.data.user;
        app.globalData.token = res.data.token;

        Toast.success('登录成功');
        
        // 延迟跳转
        setTimeout(() => {
          wx.switchTab({
            url: '/pages/index/index'
          });
        }, 1000);
      } else {
        Toast.error(res.message || '登录失败');
      }
    } catch (error) {
      Toast.hideLoading();
      console.error('游客登录失败:', error);
      Toast.error('网络错误');
    }
  },

  // 账号密码登录
  async accountLogin() {
    const { username, password } = this.data;

    if (!username || !password) {
      Toast.error('请输入用户名和密码');
      return;
    }

    Toast.loading('登录中...');

    try {
      const res = await request.post('/user-auth/login', {
        username,
        password
      });

      Toast.hideLoading();

      if (res.success) {
        // 保存token和用户信息
        wx.setStorageSync('token', res.data.token);
        wx.setStorageSync('userInfo', res.data.user);
        app.globalData.userInfo = res.data.user;
        app.globalData.token = res.data.token;

        Toast.success('登录成功');
        
        setTimeout(() => {
          wx.switchTab({
            url: '/pages/index/index'
          });
        }, 1000);
      } else {
        Toast.error(res.message || '登录失败');
      }
    } catch (error) {
      Toast.hideLoading();
      console.error('账号登录失败:', error);
      Toast.error('网络错误');
    }
  },

  // 发送验证码
  async sendSmsCode() {
    const { phone, countdown } = this.data;

    if (!phone) {
      Toast.error('请输入手机号');
      return;
    }

    if (!/^1[3-9]\d{9}$/.test(phone)) {
      Toast.error('请输入正确的手机号');
      return;
    }

    if (countdown > 0) {
      return;
    }

    this.setData({ sending: true });

    try {
      const res = await request.post('/user-auth/send-sms', {
        phone,
        type: 'login'
      });

      this.setData({ sending: false });

      if (res.success) {
        Toast.success('验证码已发送');
        
        // 开始倒计时
        this.setData({ countdown: 60 });
        const timer = setInterval(() => {
          const count = this.data.countdown - 1;
          if (count <= 0) {
            clearInterval(timer);
            this.setData({ countdown: 0 });
          } else {
            this.setData({ countdown: count });
          }
        }, 1000);
      } else {
        Toast.error(res.message || '发送失败');
      }
    } catch (error) {
      this.setData({ sending: false });
      console.error('发送验证码失败:', error);
      Toast.error('网络错误');
    }
  },

  // 手机验证码登录
  async phoneLogin() {
    const { phone, smsCode } = this.data;

    if (!phone || !smsCode) {
      Toast.error('请输入手机号和验证码');
      return;
    }

    Toast.loading('登录中...');

    try {
      const res = await request.post('/user-auth/login-sms', {
        phone,
        code: smsCode
      });

      Toast.hideLoading();

      if (res.success) {
        // 保存token和用户信息
        wx.setStorageSync('token', res.data.token);
        wx.setStorageSync('userInfo', res.data.user);
        app.globalData.userInfo = res.data.user;
        app.globalData.token = res.data.token;

        Toast.success(res.message || '登录成功');
        
        setTimeout(() => {
          wx.switchTab({
            url: '/pages/index/index'
          });
        }, 1000);
      } else {
        Toast.error(res.message || '登录失败');
      }
    } catch (error) {
      Toast.hideLoading();
      console.error('手机登录失败:', error);
      Toast.error('网络错误');
    }
  },

  // 执行登录
  doLogin() {
    const { loginType } = this.data;

    switch (loginType) {
      case 'guest':
        this.guestLogin();
        break;
      case 'account':
        this.accountLogin();
        break;
      case 'phone':
        this.phoneLogin();
        break;
    }
  },

  // 跳转到注册页面
  goToRegister() {
    wx.navigateTo({
      url: '/pages/register/register'
    });
  }
});

